package com.pet.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.pet.mapper.SysRoleMapper;
import com.pet.mapper.SysUserRoleMapper;
import com.pet.service.SysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pet.system.SysRole;
import com.pet.system.SysUserRole;
import com.pet.vo.AssginRoleVo;
import com.pet.vo.SysRoleQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author whd
 * @since 2023-07-29
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Override
    public IPage<SysRole> selectpage(IPage<SysRole> page1, SysRoleQueryVo roleQueryVo) {
        IPage<SysRole> iPage=this.baseMapper.selectPage(page1,roleQueryVo);
        return iPage;
    }

    @Override
    public void doAssign(AssginRoleVo assignRolevo) {
        //根据用户id删除原来分配的角色
        QueryWrapper<SysUserRole> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",assignRolevo.getUserId());
        sysUserRoleMapper.delete(queryWrapper);
        //获取所有角色的id
        List<Long> roleIdList =assignRolevo.getRoleIdList();
        for (Long roleId : roleIdList) {
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setUserId(assignRolevo.getUserId());
            sysUserRole.setRoleId(roleId);
            //保存
            System.out.println("");
            System.out.println("角色分配成功");
            System.out.println("");
            sysUserRoleMapper.insert(sysUserRole);
        }

    }



    @Override
    public boolean removeBatchByIds(List<Long> ids) {
        int i = this.sysUserRoleMapper.deleteBatchIds(ids);
        if (i>0){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public Map<String, Object> getRolesByUserId(Long userId) {
        //获取所有角色
        List<SysRole> roles = sysRoleMapper.selectList(null);
        //根据用户id查询
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        //获取用户已分配的角色
        List<SysUserRole> userRoles = sysUserRoleMapper.selectList(queryWrapper);
        //获取用户已分配的角色id
        List<Long> userRoleIds = new ArrayList<>();
        for (SysUserRole userRole : userRoles) {
            userRoleIds.add(userRole.getRoleId());
        }
        //创建返回的Map
        Map<String, Object> returnMap = new HashMap<>();
        returnMap.put("allRoles",roles);
        returnMap.put("userRoleIds",userRoleIds);
        return returnMap;
    }


}
